package com.sanjiahantang.ythshopping.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.GoodsCollectActivity;
import com.sanjiahantang.ythshopping.activity.MainActivity;
import com.sanjiahantang.ythshopping.activity.me.AddressListActivity;
import com.sanjiahantang.ythshopping.activity.me.ChangePasswordActivity;
import com.sanjiahantang.ythshopping.activity.me.EvaluateListActivity;
import com.sanjiahantang.ythshopping.activity.me.JsWebActivity;
import com.sanjiahantang.ythshopping.activity.me.LeaveMsgActivity;
import com.sanjiahantang.ythshopping.activity.me.LoginActivity;
import com.sanjiahantang.ythshopping.activity.me.MeAccountActivity;
import com.sanjiahantang.ythshopping.activity.me.MoreActicity;
import com.sanjiahantang.ythshopping.activity.me.MyOrderActivity;
import com.sanjiahantang.ythshopping.activity.me.RechargeActivity;
import com.sanjiahantang.ythshopping.activity.me.RegisterActivity;
import com.sanjiahantang.ythshopping.activity.me.ShareSqcodeActivity;
import com.sanjiahantang.ythshopping.activity.me.TypeOrderActivity;
import com.sanjiahantang.ythshopping.activity.me.WebActivity;
import com.sanjiahantang.ythshopping.adapter.home.MyGridView;
import com.sanjiahantang.ythshopping.config.ConfigValue;
import com.sanjiahantang.ythshopping.config.SPConfig;
import com.sanjiahantang.ythshopping.model.MeIconModel;
import com.sanjiahantang.ythshopping.model.UserInforModel;
import com.sanjiahantang.ythshopping.presenter.UserInforPresenter;
import com.sanjiahantang.ythshopping.utils.DataCleanManager;
import com.sanjiahantang.ythshopping.utils.SPUtils;
import com.sanjiahantang.ythshopping.utils.Utils;
import com.sanjiahantang.ythshopping.views.PersonalView;
import com.sanjiahantang.ythshopping.views.UserInforView;
import com.sanjiahantang.shopping.uilibrary.GridViewFixScroll;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.shopping.uilibrary.uiutils.ImageUtils;

import java.io.File;
import java.util.ArrayList;

import q.rorbin.badgeview.QBadgeView;




/**
 * 个人中心
 */
public class MeFragment extends BaseFragment implements OnItemClickListener, View.OnClickListener,
        UserInforView {

    private QuickAdapter<MeIconModel> mQuickAdapter;
    private QuickAdapter<MeIconModel> menuAdapter;
    private String[] items = {"待付款", "待发货", "待收货", "已完成"};
    private String[] menutext = {"商城订单", "我的资产", "评价晒单", "我的收藏",
            "推广二维码","我的推荐","收货地址","我的留言",
            "绑定手机","修改密码","扫码订单","预支付订单"

    };
    private int[] icons = {R.mipmap.wait_payment, R.mipmap.wait_deliver,R.mipmap.wait_receive, R.mipmap.after_sale};

    private int[] menuicons = { R.drawable.icon_order,R.drawable.icon_assets,R.drawable.icon_evaluate,R.drawable.icon_collect,
            R.drawable.icon_generalize,R.drawable.myrem_qr,R.drawable.icon_address,R.drawable.icon_message,
            R.drawable.bandphone,R.drawable.changepwd,R.drawable.saomaorder,R.drawable.yudingdan};
    private MeIconModel miModel;
    private ImageView headphoto;
    private LinearLayout lineLay_not_login;
    private LinearLayout lineLay_login;

    private TextView txtNickname;
    private TextView txtExpenser;
    private TextView txtTianhe;
    private TextView txtExarch;
    GridViewFixScroll gridView;
    MyGridView menuGrid;
    private UserInforPresenter uPresenter;

    private PersonalView mPersonalView;

    private View mView,llRoot;

    public void setLmIndex(int lmIndex) {
        this.lmIndex = lmIndex;
    }

    //商家底下按鈕位置
    private int lmIndex = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("TEST", "创建MeFragment");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_me, container, false);
        return mView;
    }


    @Override
    protected void initView() {
        mView.findViewById(R.id.titleView).setVisibility(View.GONE);
        uPresenter = new UserInforPresenter(this);
        llRoot = mView.findViewById(R.id.llRoot);
        ArrayList<MeIconModel> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miModel = new MeIconModel();
            miModel.setItems(items[i]);
            miModel.setIcon(icons[i]);
            list.add(miModel);
        }

        ArrayList<MeIconModel> menulist = new ArrayList<>();
        for (int i = 0; i < menutext.length; i++) {
            miModel = new MeIconModel();
            miModel.setItems(menutext[i]);
            miModel.setIcon(menuicons[i]);
            menulist.add(miModel);
        }

        txtExpenser= (TextView) mView.findViewById(R.id.tv_my_expenser);
        txtTianhe= (TextView) mView.findViewById(R.id.tv_my_tianhe);
        txtExarch= (TextView) mView.findViewById(R.id.tv_my_exarch);
        gridView = (GridViewFixScroll) mView.findViewById(R.id.gridview);
        menuGrid= (MyGridView) mView.findViewById(R.id.gv_my_menu);
        mQuickAdapter = new QuickAdapter<MeIconModel>(getActivity(), R.layout.me_grid_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIconModel item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());
                ImageView orderType = helper.getView(R.id.imgIcon);
                if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                    new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                            .setBadgeNumber(Integer.valueOf(item.getNum()))
                    .setGravityOffset(-2,-2, true)
                    .setBadgeTextSize(8, true);
                }
//
            }
        };
        menuAdapter = new QuickAdapter<MeIconModel>(getActivity(), R.layout.me_grid_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIconModel item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());

            }
        };



        mQuickAdapter.addAll(list);
        menuAdapter.addAll(menulist);
        gridView.setAdapter(mQuickAdapter);
        gridView.setOnItemClickListener(this);
        menuGrid.setAdapter(menuAdapter);
        menuGrid.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (network()) {
                    if (!ConfigValue.DATA_KEY.equals("")) {
                        switch (position)
                        {
                            case 0://我的订单
                                Intent itOrder = new Intent(getActivity(), MyOrderActivity.class);
                                startActivity(itOrder);
                                break;
                            case 1://我的资产
                                Intent itrecharge = new Intent(getActivity(), RechargeActivity.class);
                                startActivity(itrecharge);
                                break;
                            case 2://评价晒单
                                Intent Eintent=new Intent(getActivity(), EvaluateListActivity.class);
                                startActivity(Eintent);
                                break;
                            case 3://我的收藏
                                Intent itcollect = new Intent(getActivity(), GoodsCollectActivity.class);
                                startActivity(itcollect);
                                break;
                            case 4://二维码
                                Intent intent=new Intent(getActivity(), ShareSqcodeActivity.class);
                                startActivity(intent);
                                break;
                            case 5://我的推荐

                                context.startActivity(new Intent(context, WebActivity.class)
                                        .putExtra("url",ConfigValue.IMG_IP+"/mobile/user.php?act=compound_my_recommend&from_app=2&key="+ConfigValue.DATA_KEY)
                                        .putExtra("type","1")
                                        .putExtra("title","我的推荐")
                                );
                                break;
                            case 6://收货地址
                                Intent itAddress = new Intent(context, AddressListActivity.class);
                                startActivity(itAddress);
                                break;
                            case 7://我的留言
                                Intent intentleavemsg=new Intent(context, LeaveMsgActivity.class);
                                startActivity(intentleavemsg);
                                break;
                            case 8://绑定手机
                                context.startActivity(new Intent(context, WebActivity.class)
                                        .putExtra("url",ConfigValue.IMG_IP+"/mobile/user.php?act=compound_bind_mobile&from_app=2&key="+ConfigValue.DATA_KEY)
                                        .putExtra("type","1")
                                        .putExtra("title","绑定手机")
                                );
                                break;
                            case 9://修改密码
                                startActivity(new Intent(context, ChangePasswordActivity.class));
                                break;
                            case 10://扫码订单
                                Intent intenturl = new Intent(context, WebActivity.class);
                                String url;
                                if(ConfigValue.uInfor.getShop_order_url().indexOf("?")>0)
                                {
                                    url= ConfigValue.IMG_IP+ConfigValue.uInfor.getShop_order_url()+"&from_app=2&key="+ConfigValue.DATA_KEY;
                                }else {
                                    url= ConfigValue.IMG_IP+ConfigValue.uInfor.getShop_order_url()+"?from_app=2&key="+ConfigValue.DATA_KEY;
                                }
                                intenturl.putExtra("url",url);
                                intenturl.putExtra("type","1");
                                intenturl.putExtra("title","扫码订单");
                                context.startActivity(intenturl);
                                break;
                            case 11://预支付订单

                                Intent intenturl2 = new Intent(context, WebActivity.class);
                                String url2;
                                if(ConfigValue.uInfor.getShop_order_url().indexOf("?")>0)
                                {
                                    url2= ConfigValue.IMG_IP+ConfigValue.uInfor.getShop_order_url()+"&from_app=2&key="+ConfigValue.DATA_KEY + "&type=2";
                                }else {
                                    url2= ConfigValue.IMG_IP+ConfigValue.uInfor.getShop_order_url()+"?from_app=2&key="+ConfigValue.DATA_KEY + "&type=2";
                                }
                                intenturl2.putExtra("url",url2);
                                intenturl2.putExtra("type","1");
                                intenturl2.putExtra("title","预支付订单");
                                context.startActivity(intenturl2);
                                break;

                        }
                    }else {
                        toLogin();
                    }
                }

            }
        });
        lineLay_not_login = (LinearLayout) mView.findViewById(R.id.lineLay_not_login);
        lineLay_login = (LinearLayout) mView.findViewById(R.id.lineLay_login);

        headphoto = (ImageView) mView.findViewById(R.id.imgHead);
        txtNickname = (TextView) mView.findViewById(R.id.txtNickname);
        mView.findViewById(R.id.txtLogin).setOnClickListener(this);
        mView.findViewById(R.id.txtRegister).setOnClickListener(this);
        mView.findViewById(R.id.F_right).setOnClickListener(this);
        mView.findViewById(R.id.rlQuit).setOnClickListener(this);
        mView.findViewById(R.id.lineLay_ll).setOnClickListener(this);


    }

    //图片保存在本地，查看本地有无头像，若有则显示，没有则不显示

    private void initHeadPhoto() {
        String filePath = ConfigValue.HEAD_PHOTO_DIR + File.separator + ConfigValue.uInfor.getNick_name() + ".jpg";
        File file = new File(filePath);
        if (file.exists()) {
            Bitmap bitmap = ImageUtils.compressBitmap(filePath, 320, 320);
            if (bitmap != null) {
                headphoto.setVisibility(View.VISIBLE);
                headphoto.setImageBitmap(bitmap);
                // bitmap.recycle();
            }

        }
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view,
                            int position, long id) {
        if (network()) {
            if (!ConfigValue.DATA_KEY.equals("")) {
                       switch (position) {
                           //待付款
                           case 0:
                               Intent intent = new Intent(context, TypeOrderActivity.class);
                               intent.putExtra("type", 0);
                               startActivity(intent);
                               break;
                           //待发货
                           case 1:
                               Intent intent1 = new Intent(context, TypeOrderActivity.class);
                               intent1.putExtra("type", 1);
                               startActivity(intent1);
                               break;
                           //待收货
                           case 2:
                               Intent intent2 = new Intent(context, TypeOrderActivity.class);
                               intent2.putExtra("type", 2);
                               startActivity(intent2);
                               break;
                           //已完成
                           case 3:
                               Intent intent3 = new Intent(context, TypeOrderActivity.class);
                               intent3.putExtra("type", 3);
                               startActivity(intent3);
                               break;




               }
            } else
                toLogin();
        }
    }

    private void toLogin() {
        Intent itLogin = new Intent(getActivity(), LoginActivity.class);
        startActivity(itLogin);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //设置
            case R.id.F_right:
                Intent itMore = new Intent(getActivity(), MoreActicity.class);
                startActivity(itMore);
                break;
            //消息
//			case R.id.ensure:
//				if(!ConfigValue.DATA_KEY.equals("")) {
//					Intent itMessage = new Intent(getActivity(), MessageActivity.class);
//					startActivity(itMessage);
//				}else
//					toLogin();
//				break;
            //我的账户
            case R.id.lineLay_ll:
                if (network()) {
                    Intent intent = new Intent(getActivity(), MeAccountActivity.class);
                    startActivity(intent);
                }
                break;
            //登陆
            case R.id.txtLogin:
                toLogin();
                break;
            //注册
            case R.id.txtRegister:
                Intent itRegister = new Intent(getActivity(), RegisterActivity.class);
                startActivity(itRegister);
                break;


            //意见
           /* case R.id.rlIdea:
                if (network()) {
                    Intent itFeedback = new Intent(context, FeedbackActivity.class);
                    startActivity(itFeedback);
                }
                break;*/
            //退出
            case R.id.rlQuit:
                if (!ConfigValue.DATA_KEY.equals("")) {
                    Utils.showDialog(getActivity(), "提示", "确定退出登录吗？", "", "", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            switch (view.getId()) {
                                case R.id.txtDialogCancel:
                                    Utils.dismissDialog();
                                    break;
                                case R.id.txtDialogSure:
                                    ConfigValue.uInfor = null;
                                    ConfigValue.DATA_KEY = "";
                                    SPUtils.remove(getActivity(), SPConfig.KEY);
                                    lineLay_not_login.setVisibility(View.VISIBLE);

                                    lineLay_login.setVisibility(View.GONE);
                                    mPersonalView.setCartGoodsNums("0");
                                    initGrid();
                                    headphoto.setVisibility(View.INVISIBLE);
                                    mView.findViewById(R.id.rlQuit).setVisibility(View.GONE);
                                    llRoot.setVisibility(View.VISIBLE);
                                    DataCleanManager.cleanApplicationData(getContext(), "/data/data/"
                                            + getContext().getPackageName());
                                    Utils.dismissDialog();
                                    break;
                            }
                        }
                    });
                }
                break;

          /*  case R.id.scan_orders:
                if (network()){
                    if (!ConfigValue.DATA_KEY.equals("")){
                        Intent sintent = new Intent(context, ScanOrdersActivity.class);
                        startActivity(sintent);
                    }else {
                        toLogin();
                    }
                }
                break;*/

        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //实例化mPersonalView
        mPersonalView = (PersonalView) context;
    }

    @Override
    public void inforData(UserInforModel model) {
        if (model.getCode().equals("1")) {
            ConfigValue.uInfor = model.getData().get(0);
            if (model.getData().get(0).getLmshop().equals("1") )
            {
                if(ConfigValue.LM_FIRST){
                    ConfigValue.LM_FIRST = false;
                    llRoot.setVisibility(View.GONE);
                    Intent intent = new Intent(context, JsWebActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("url", "mobile/user.php?act=default");
                    intent.putExtras(bundle);
                    ((Activity)context).overridePendingTransition(0, 0);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    ((Activity)context).startActivityForResult(intent, MainActivity.RESULT_MY);
                    lmIndex = 0;
                }else{
                    switch (lmIndex){
                        case 4:
                            ConfigValue.LM_FIRST = false;
                            Intent intent = new Intent(context, JsWebActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                            ((Activity)context).overridePendingTransition(0, 0);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("url", "mobile/user.php?act=default");
                            intent.putExtras(bundle);
                            ((Activity)context).startActivityForResult(intent, MainActivity.RESULT_MY);
                            lmIndex = 0;
                            break;
                        default:
                            ((MainActivity)context).setFragmentIndex(lmIndex);
                            break;
                    }
                }



            }else {
                showInfor();
            }

        } else {
            llRoot.setVisibility(View.VISIBLE);
            if (model.getCode().equals("-220")) {
                SPUtils.remove(getActivity(), SPConfig.KEY);
            }
            Utils.showToast(context, model.getMsg());
        }

    }

    private void showInfor() {
        llRoot.setVisibility(View.VISIBLE);
        lineLay_not_login.setVisibility(View.GONE);

        lineLay_login.setVisibility(View.VISIBLE);
        mView.findViewById(R.id.rlQuit).setVisibility(View.VISIBLE);
        txtExpenser.setText(ConfigValue.uInfor.getUser_money());
        txtExarch.setText(ConfigValue.uInfor.getXfb_money());
        txtTianhe.setText(ConfigValue.uInfor.getIntegration());
        txtNickname.setText(ConfigValue.uInfor.getNick_name());
//        txtIntegral.setText(ConfigValue.uInfor.getIntegration());
//        attention.setText(ConfigValue.uInfor.getAttention());
//        balance.setText(ConfigValue.uInfor.getUser_money());
        ArrayList<MeIconModel> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miModel = new MeIconModel();
            miModel.setItems(items[i]);
            miModel.setIcon(icons[i]);
            switch (i) {
                case 0:
                    miModel.setNum(ConfigValue.uInfor.getPay());
                    break;
                case 1:
                    miModel.setNum(ConfigValue.uInfor.getShipping_send());
                    break;
                case 2:
                    miModel.setNum(ConfigValue.uInfor.getShipping());
                    break;
                case 3:
                    miModel.setNum(ConfigValue.uInfor.getFinished());
                    break;
            }
            list.add(miModel);
        }

        mQuickAdapter= new QuickAdapter<MeIconModel>(getActivity(), R.layout.me_grid_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIconModel item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());
                ImageView orderType = helper.getView(R.id.imgIcon);
                if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                    new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                            .setBadgeNumber(Integer.valueOf(item.getNum()))
                            .setGravityOffset(-2,-2, true)
                            .setBadgeTextSize(8, true);
                }
//
            }
        };
        mQuickAdapter.addAll(list);
        gridView.setAdapter(mQuickAdapter);
        initHeadPhoto();
    }

    private void initGrid() {
        ArrayList<MeIconModel> list = new ArrayList<>();
        for (int i = 0; i < items.length; i++) {
            miModel = new MeIconModel();
            miModel.setItems(items[i]);
            miModel.setIcon(icons[i]);
            list.add(miModel);
        }


        mQuickAdapter= new QuickAdapter<MeIconModel>(getActivity(), R.layout.me_grid_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, MeIconModel item) {
                helper.getView(R.id.imgIcon).setBackgroundResource(item.getIcon());
                helper.setText(R.id.txtItem, item.getItems());
                ImageView orderType = helper.getView(R.id.imgIcon);
                if (!TextUtils.isEmpty(item.getNum()) && !item.getNum().equals("null") && Integer.valueOf(item.getNum())!=0){
                    new QBadgeView(context).bindTarget(orderType).setBadgeGravity(Gravity.TOP | Gravity.END)
                            .setBadgeNumber(Integer.valueOf(item.getNum()))
                            .setGravityOffset(-2,-2, true)
                            .setBadgeTextSize(8, true);
                }
//
            }
        };
        mQuickAdapter.addAll(list);
        gridView.setAdapter(mQuickAdapter);

    }

    private boolean network() {
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(getContext())) {
            Utils.showDialog(getActivity(), "提示", "您现在的网络不是太好哦！", "", "重试", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    switch (view.getId()) {
                        case R.id.txtDialogCancel:
                            Utils.dismissDialog();
                            break;
                        case R.id.txtDialogSure:
                            Utils.dismissDialog();
                            onResume();
                            break;
                    }
                }
            });
            return false;
        }
        return true;
    }

    private void initUserData() {
//		if(null != ConfigValue.uInfor){
//			showInfor();
//		}else{
        ConfigValue.DATA_KEY = (String) SPUtils.get(getActivity(), SPConfig.KEY, "");
        if (ConfigValue.DATA_KEY != null && !ConfigValue.DATA_KEY.equals("")) {
            uPresenter.loadInfor(getActivity());
        } else {
            llRoot.setVisibility(View.VISIBLE);
            lineLay_not_login.setVisibility(View.VISIBLE);

            lineLay_login.setVisibility(View.GONE);
            mView.findViewById(R.id.rlQuit).setVisibility(View.GONE);
        }
//		}
    }

    @Override
    public void onResume() {
        if (network())
            initUserData();
        super.onResume();
    }


}
